package com.jmp.video;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Lists;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import one.stand.util.OneListUtil;

import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * @author cjr
 */
@Slf4j
public class VideoClientImpl implements VideoClient {

    private Credential cred;
    private VodClient client;

    public VideoClientImpl() {
        cred = new Credential("AKIDSggQyQFxwhHbu5vqgOwMchdO2E0AjsHS", "FYcT4VDvSkrlT4VggbP3UmslT4XZMxJU");
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("vod.tencentcloudapi.com");
        httpProfile.setConnTimeout(10);//10s超时
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        client = new VodClient(cred, "", clientProfile);
    }

    @Override
    public String getSign(String userId) {
        Signature sign = new Signature();
        sign.setSecretId(cred.getSecretId());
        sign.setSecretKey(cred.getSecretKey());
        sign.setCurrentTime(System.currentTimeMillis() / 1000);
        sign.setRandom(new Random().nextInt(java.lang.Integer.MAX_VALUE));
        sign.setSignValidDuration(7776000);//90天
        sign.setClassId("691633");//分类ID: 691633:短视频
        sign.setProcedure("jmp_CoverFirstImage");//任务流ID:

        try {
            return sign.getUploadSignature(userId);
        } catch (Exception e) {
            log.error("获取签名失败", e);
        }

        return null;
    }

    @Override
    public PullEventsVo pullEvents() {
        String params = "{}";
        PullEventsRequest req = PullEventsRequest.fromJsonString(params, PullEventsRequest.class);
        try {
            PullEventsResponse resp = client.PullEvents(req);
            List<PullEventsVo.File> fileUploadList = Lists.newArrayList();
            List<String> eventHandles = Lists.newArrayList();
            for (EventContent eventContent : resp.getEventSet()) {
                switch (eventContent.getEventType()) {
                    case "NewFileUpload":
                        if (NumberUtil.isInteger(eventContent.getFileUploadEvent().getMediaBasicInfo().getSourceInfo().getSourceContext())) {
                            fileUploadList.add(PullEventsVo.File.builder()
                                    .eventHandle(eventContent.getEventHandle())
                                    .fileId(eventContent.getFileUploadEvent().getFileId())
                                    .name(eventContent.getFileUploadEvent().getMediaBasicInfo().getName())
                                    .coverUrl(eventContent.getFileUploadEvent().getMediaBasicInfo().getCoverUrl())
                                    .mediaUrl(eventContent.getFileUploadEvent().getMediaBasicInfo().getMediaUrl())
                                    .sourceContext(eventContent.getFileUploadEvent().getMediaBasicInfo().getSourceInfo().getSourceContext())
                                    .videoDuration(Objects.nonNull(eventContent.getFileUploadEvent().getMetaData()) ? eventContent.getFileUploadEvent().getMetaData().getDuration() : null)
                                    .build()
                            );
                        } else {//其他视频上传
                            eventHandles.add(eventContent.getEventHandle());//默认不处理
                        }
                        break;
                    case "ProcedureStateChanged"://任务流状态变更事件
                        MediaProcessTaskResult[] mediaProcessTaskResults = eventContent.getProcedureStateChangeEvent().getMediaProcessResultSet();
                        if (ArrayUtil.isNotEmpty(mediaProcessTaskResults)) {//视频处理任务的执行状态与结果
                            for (MediaProcessTaskResult mediaProcessTaskResult : mediaProcessTaskResults) {
                                if ("SnapshotByTimeOffset".equals(mediaProcessTaskResult.getType())) {//时间点截图
                                    mediaProcessTaskResult.getSnapshotByTimeOffsetTask().getStatus();
                                    break;
                                }
                            }
                        }
                        break;
                    default:
                        eventHandles.add(eventContent.getEventHandle());//默认不处理
                        break;
                }
            }
            if (OneListUtil.isNotEmpty(eventHandles)) {
                confirmEvents(eventHandles);
            }
            return PullEventsVo.builder()
                    .fileUploadEvents(fileUploadList)
                    .build();
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage());
        }

        return null;
    }

    @Override
    public void confirmEvents(List<String> eventHandles) {
        try {
            int page = (eventHandles.size() + 16) / 16;
            for (int i = 0; i < page; i++) {
                List<String> sub = CollUtil.page(i, 16, eventHandles);

//                String params = "{\"EventHandles\":[\"阿斯蒂芬\",\"sdf\",\"ad\"]}";
                ConfirmEventsRequest req = new ConfirmEventsRequest();
                req.setEventHandles(ArrayUtil.toArray(sub, String.class));
                ConfirmEventsResponse resp = client.ConfirmEvents(req);
            }
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void delete(String fileId) {
        DeleteMediaRequest req = new DeleteMediaRequest();
        req.setFileId(fileId);
        try {
            DeleteMediaResponse resp = client.DeleteMedia(req);
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void forbid(String fileId) {
        ForbidMediaDistributionRequest req = new ForbidMediaDistributionRequest();
        req.setFileIds(new String[]{fileId});
        try {
            ForbidMediaDistributionResponse resp = client.ForbidMediaDistribution(req);
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage(), e);
        }
    }
}
